package cn.mdmbct.douyin.common.utils;

import cn.mdmbct.douyin.common.enums.ErrorCode;
import cn.mdmbct.douyin.common.exception.ApiResponseFailedException;
import cn.mdmbct.douyin.common.response.DefaultResponseData;
import cn.mdmbct.douyin.common.response.OpenApiResponse;
import com.alibaba.fastjson.JSONObject;

/**
 * @author mdmbct  mdmbct@outlook.com
 * @date 5/10/2021 22:32 PM
 * @modified mdmbct
 * @since 1.0
 */
public class ApiResultHandler {


    public static <T extends OpenApiResponse> T handleApiResponse(String responseResult, Class<T> responseClass) {
        return JSONObject.parseObject(responseResult, responseClass);
    }

    @SuppressWarnings("unchecked")
    public static <T extends OpenApiResponse, D extends DefaultResponseData> D handleApiResponseData(String responseResult,
                                                                                                     Class<T> responseClass) throws ApiResponseFailedException {
        T t = JSONObject.parseObject(responseResult, responseClass);

        if (t.getData().getErrorCode() == ErrorCode.SUCCESS.getValue()) {
            return (D) t.getData();
        }

        throw new ApiResponseFailedException(t.getErrorMsg());
    }
}
